//处理value为0的时候
import { useEffect, useRef, useState } from "react";
import { doc } from "prettier";

// import {clearTimeout} from "timers";
// 这个导入页面就崩了？

//any是有害的
//unknown
// isFalsy(1)
// isFalsy({})
// isFalsy(undefined)
// unknown 可以被任何赋值，但是不可以赋给任何值,也不能读取任何方法 比如：
// let value:unknown
// value.not 不能读取任何方法
// let valueNumber = 1
// valueNumber = value 报错
//never
// const func = () => {
//   throw new Error()
// }
export const isFalsy = (value: unknown) => (value === 0 ? false : !value);

export const isVoid = (value: unknown) =>
  value === undefined || value === null || value === " ";

// let a:object
// a={name:'jack'}    [key:string]:unknown}
// a=()=>{}
// a=new RegExp('')

// 值为空的键删掉
export const cleanObject = (object: { [key: string]: unknown }) => {
  // Object.assign({},object)
  const result = { ...object };

  Object.keys(result).forEach((key) => {
    //0
    // @ts-ignore 暂时不管
    const value = result[key];
    if (isVoid(value)) {
      // @ts-ignore
      delete result[key];
    }
  });
  return result;
};

//去掉满屏的空数组
export const useMount = (callback: () => void) => {
  useEffect(() => {
    // eslint-disable-next-line
    callback();
    //  TODO 依赖项里加上callback会造成无限循环，这个和useCallback以及useMemo有关
  }, []);
};

//后面用泛型来规范类型
//把value转化成debouncedValue
export const useDebounce = <V>(value: V, delay?: number) => {
  const [debouncedValue, setDebouncedValue] = useState(value);
  // console.log(value.mayNotExist)报错

  useEffect(() => {
    //每次在value变化以后，设置一个定时器
    // eslint-disable-next-line
    const timeout = setTimeout(() => setDebouncedValue(value), delay);
    //每次在上一个useEffect处理完以后再运行
    return () => clearTimeout(timeout);
  }, [value, delay]);

  return debouncedValue;
};

//debounce原理
// const debounce = (func,delay) => {
//   let timeout;
//   return(...param) => {
//     if(timeout){
//       clearTimeout(timeout);
//     }
//     timeout = setTimeout(function() {
//       func(...param);
//     },delay);
//   }
// }
// const log = debounce( ()=> console.log('call'),5000)
// log() //undefined timeout#1
// log() //清除timeout#1 timeout=timeout#2
// log() //清除timeout+2 timeout=timeout#3
// 只5秒后执行输出call

export const useDocumentTitle = (
  title: string,
  keepOnUnmount: boolean = true
) => {
  const oldTitle = useRef(document.title).current;

  useEffect(() => {
    document.title = title;
  }, [title]);

  useEffect(() => {
    if (!keepOnUnmount) {
      document.title = oldTitle;
    }
  }, [keepOnUnmount, oldTitle]);
};

export const resetRoute = () => (window.location.href = window.location.origin);

/*返回组件的挂载状态，*/
export const useMountedRef = () => {
  const mountedRef = useRef(false);

  useEffect(() => {
    mountedRef.current = true;
    return () => {
      mountedRef.current = false;
    };
  });

  return mountedRef;
};
